package com.it.travel01.webadvice;

import com.it.travel01.pojo.User;
import lombok.extern.slf4j.Slf4j;
import org.springframework.web.bind.annotation.ControllerAdvice;
import org.springframework.web.bind.annotation.ExceptionHandler;
import org.springframework.web.method.HandlerMethod;

import javax.servlet.http.HttpServletRequest;
import java.lang.reflect.Method;

@ControllerAdvice
@Slf4j
public class GlobalExceptionHandler {

    /**
     * log4j记录当前登录用户信息、请求路径信息、处理器方法信息、错误信息等信息；
     * @param ex
     * @return
     */
    @ExceptionHandler(RuntimeException.class)
    public String handlerException(RuntimeException ex, HttpServletRequest request, HandlerMethod method){
        //获取登录信息
        User sUser = (User) request.getSession().getAttribute("CUR_USER");
        String curUserName=sUser==null?null:sUser.getName();
        //获取当前出错的url请求地址，方便开发人员快速定位
        String reqpath = request.getServletPath();
        //获取处理器方法信息
        Method curMethod = method.getMethod();
        String absMethodName=curMethod.getDeclaringClass().getName()+"."+curMethod.getName();
        //获取信息
        String errorMsg = ex.getMessage();
        log.info("前登录用户信息:{},请求路径信息{},处理器方法信息:{},错误信息:{}",curUserName,reqpath,absMethodName,errorMsg);
        return "redirect:/error.html";
    }
}
